import React, { Component } from 'react';
import { getMultiLang, createPage, cardCache, toast, promptBox } from 'nc-lightapp-front';
import Inspection from 'epmp/exports/components/Inspection';
import SearchModl from '../../components/search-modal';
import config from './config';
import {
    onSearchButtonClick,
    onPageButtonClick,
    onTablePageChange,
    onTableRowDoubleClick,
    onTableButtonClick,
    onTableSelectChange
} from './events';
import api from '../../common/api';

const { setDefData, getDefData } = cardCache;

class Page extends Component {
    constructor(props) {
        super(props);
        props.use.search(config.headcode);
        props.use.table(config.bodycode);
        this.state = {
            multilang: {},
            isInspectionShowed: false,
            inspectionSourceData: {}
        };
        // TODO 缓存多语
    }

    componentDidMount() {
        this.initTempAndLang();
    }

    initTempAndLang() {
        const props = this.props;
        getMultiLang({
            ...config.multilang,
            callback: (json) => {
                this.setState({ multilang: json }, () => {
                    props.createUIDom({ pagecode: config.pagecode }, (data) => {
                        console.log('=====template', data);
                        this.setButton(data.button);
                        this.setMeta(data.template, data.button);
                    });
                });
            }
        });
    }

    setMeta(meta, button) {
        const props = this.props;
        // const { setPageStatus } = this.props;
        // meta[config.bodycode].status = 'browse';
        setDefData(`${config.headcode}_oid`, config.datasource, meta[config.headcode].oid);

        meta[config.headcode].items.forEach((item) => {
            if (item.attrcode === 'pk_org') {
                item.queryCondition = function () {
                    return {
                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.OrgTreeRefSqlBuilder',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            }
            // else if (item.attrcode === 'djrq') {
            //     item.initialvalue = {
            //         display: '今日~日日',
            //         value: '#day(0)#,#day(0)#'
            //     };
            // }
        });

        meta[config.bodycode].items.push({
            label: this.state.multilang['opr_title'],
            itemtype: 'customer',
            attrcode: 'opr',
            width: '140px',
            visible: true,
            fixed: 'right',
            render: (text, record, index) => {
                const buttonArray = ['table_view'];
                if (record.src_type.value === '0') {
                    if (record.billstatus.value === '0') {
                        buttonArray.push('table_edit', 'table_delete');
                    } else if (record.billstatus.value === '1') {
                        buttonArray.push('table_edit', 'table_delete', 'table_approve');
                    } else if (record.billstatus.value === '3') {
                        buttonArray.push('table_unapprove');
                    }
                }

                return props.button.createOprationButton(buttonArray, {
                    area: config.innerButtonArea,
                    buttonLimit: 3,
                    onButtonClick: (props, key) => onTableButtonClick.call(this, props, key, text, record, index)
                });
            }
        });
        props.meta.setMeta(meta, () => {
            this.initPage();
        });
    }

    setButton(button) {
        const props = this.props;
        props.button.setButtons(button);
        props.button.setPopContent(['table_delete'], '确认要执行该操作吗？');
    }

    initPage() {
        const props = this.props;
        const searchVal = getDefData(config.searchCache, config.datasource);
        this.setPageStatus();
        if (searchVal && searchVal.conditions) {
            this.props.search.setSearchValue(config.headcode, searchVal);
            this.loadData();
        }

        if (!getDefData('pk_org', config.datasourceCommon)) {
            api.getUserInfo().then((data) => {
                setDefData('pk_org', config.datasourceCommon, data.pk_org);
            });
        }

        this.props.search.setSearchValByField(config.headcode, 'djrq', {
            display: '今日~今日',
            value: '#day(0)#,#day(0)#'
        });
    }

    delete(record) {
        const props = this.props;
        promptBox({
            color: 'warning',
            title: this.state.multilang['delete'] /* 国际化处理： 删除*/,
            content: this.state.multilang['confirm_delete_select'] /* 国际化处理： ​​确定要删除所选数据吗？*/,
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: this.state.multilang['confirm'] /* 国际化处理： 确定*/,
            cancelBtnName: this.state.multilang['cancel'] /* 国际化处理： 取消*/,
            beSureBtnClick: () => {
                let pks = '';
                if (record) {
                    pks = record.pk_costshare.value;
                } else {
                    const checkedRows = props.table.getCheckedRows(config.bodycode);
                    if (checkedRows.length !== 1) {
                        toast({
                            color: 'warning',
                            content: '请选中一行'
                        });
                        return;
                    }
                    pks = checkedRows.map((item) => item.data.values.pk_costshare.value).join(',');
                }
                api.deleteCostShare({ pks }).then((data) => {
                    toast({
                        color: 'success',
                        content: this.state.multilang['operate_success']
                    });
                    // TODO 优化处理本地数据
                    this.loadData();
                });
            }
        });
    }

    approve(record) {
        const props = this.props;
        let pks = '';
        if (record) {
            pks = record.pk_costshare.value;
        } else {
            const checkedRows = props.table.getCheckedRows(config.bodycode);
            if (checkedRows.length !== 1) {
                toast({
                    color: 'warning',
                    content: '请选中一行'
                });
                return;
            }
            pks = checkedRows.map((item) => item.data.values.pk_costshare.value).join(',');
        }
        api.approveCostShare({ pks, pagecode: config.pagecode, from: 'list' }).then((data) => {
            toast({
                color: 'success',
                content: this.state.multilang['operate_success']
            });
            // TODO 优化处理本地数据
            this.loadData();
        });
    }

    cancelApprove(record) {
        const props = this.props;
        let pks = '';
        if (record) {
            pks = record.pk_costshare.value;
        } else {
            const checkedRows = props.table.getCheckedRows(config.bodycode);
            if (checkedRows.length !== 1) {
                toast({
                    color: 'warning',
                    content: '请选中一行'
                });
                return;
            }
            pks = checkedRows.map((item) => item.data.values.pk_costshare.value).join(',');
        }
        api.cancelApprovalCostShare({ pks, pagecode: config.pagecode, from: 'list' }).then((data) => {
            toast({
                color: 'success',
                content: this.state.multilang['operate_success']
            });
            // TODO 优化处理本地数据
            this.loadData();
        });
    }

    setPageStatus() {
        const props = this.props;
        props.button.setButtonDisabled(['more', 'edit', 'delete', 'approve_group'], true);
        props.table.selectAllRows(config.bodycode, false);
    }

    loadData() {
        const props = this.props;
        const pageInfo = props.table.getTablePageInfo(config.headcode);
        const querycondition = getDefData(config.searchCache, config.datasource);
        const oid = getDefData(`${config.headcode}_oid`, config.datasource);

        const params = {
            oid,
            pageInfo,
            querycondition,
            appcode: config.appcode,
            queryAreaCode: config.headcode,
            pagecode: config.pagecode,
            querytype: 'tree'
        };

        return api.getCostShareList(params).then((data) => {
            // 按钮初始化
            if (!data) {
                toast({
                    color: 'warning',
                    content: this.state.multilang['query_none_message']
                }); /* 国际化处理： 未查询出符合条件的数据*/
                props.table.setAllTableData(config.bodycode, { rows: [] });
                return;
            }

            toast({
                color: 'success',
                content: this.state.multilang['query_total_message'].replace('$_$', data[config.bodycode].rows.length)
            }); /* 国际化处理： 查询成功，共,条*/

            this.setData(data);
        });
    }

    setData(data) {
        const props = this.props;
        // TODO 调研缓存以及 allpks 的用法
        props.table.setAllTableData(config.bodycode, data[config.bodycode]);
    }

    render() {
        const { table, button, search, modal, BillHeadInfo } = this.props;
        const { NCCreateSearch } = search;
        const { createModal } = modal;
        const { createBillHeadInfo } = BillHeadInfo;
        const { createSimpleTable } = table;

        return (
            <div className="nc-single-table">
                <div className="nc-singleTable-header-area">
                    <div className="header-title-search-area">
                        {createBillHeadInfo({
                            title: this.state.multilang['list_page_title'],
                            initShowBackBtn: false
                        })}
                    </div>
                    <div className="header-button-area">
                        {button.createButtonApp({
                            area: config.pageButtonArea,
                            buttonLimit: 8,
                            onButtonClick: onPageButtonClick.bind(this)
                        })}
                    </div>
                </div>
                <div className="nc-singleTable-search-area">
                    {NCCreateSearch(config.headcode, { clickSearchBtn: onSearchButtonClick.bind(this) })}
                </div>
                <div className="nc-singleTable-table-area">
                    {createSimpleTable(config.bodycode, {
                        handlePageInfoChange: onTablePageChange.bind(this),
                        onRowDoubleClick: onTableRowDoubleClick.bind(this),
                        selectedChange: onTableSelectChange.bind(this),
                        dataSource: config.datasource,
                        showIndex: true,
                        showCheck: true
                    })}
                </div>

                <SearchModl
                    ref={(item) => (this.searchModal = item)}
                    multilang={this.state.multilang}
                    {...this.props}
                />

                {this.state.isInspectionShowed && (
                    <Inspection
                        show={this.state.isInspectionShowed}
                        sourceData={this.state.inspectionSourceData}
                        cancel={() => this.setState({ isInspectionShowed: false })}
                        affirm={() => this.setState({ isInspectionShowed: true })}
                    />
                )}
            </div>
        );
    }
}

export default createPage({
    // billinfo: {
    //     billtype: 'grid',
    //     pagecode: config.pagecode,
    //     headcode: config.headcode
    // },
    mutiLangCode: config.mutiLangCode,
    initTemplate: null
})(Page);
